package com.wenmingliang.blog.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wenmingliang.blog.dao.mapper.ArticleMapper;
import com.wenmingliang.blog.dao.pojo.Article;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

@Component
public class ThreadService {

    // 期望此操作在线程池里执行,不会影响主线程
    @Async("taskExecuter")
    public void updateArticleViewCount(ArticleMapper articleMapper, Article article) {
        int viewCounts = article.getViewCounts();
        Article articleUpdate = new Article();
        articleUpdate.setViewCounts(viewCounts +  1);
        LambdaQueryWrapper<Article> articleLambdaQueryWrapper = new LambdaQueryWrapper<>();
        articleLambdaQueryWrapper.eq(Article::getId, article.getId());
        // 设置一个为了在多线程环境下线程安全
        articleLambdaQueryWrapper.eq(Article::getViewCounts, viewCounts);
        // update article set view_count=100 where view_count=99 and id=11

        articleMapper.update(articleUpdate,articleLambdaQueryWrapper);
        try {
            Thread.sleep(10000);
            System.out.println("更新完成了***********************************************");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
